﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;

namespace RMS.Common
{

    /// <summary>
    /// 文件或文件夹操作帮助类
    /// </summary>
    public class FileHelper
    {

        /// <summary>
        /// 检查文件是否存在，不存在则创建目录和空文件
        /// </summary>
        /// <param name="path">文件全路径</param>
        public static void CheckFilePath(string path)
        {
            if (!File.Exists(path))
            {
                string map = Path.GetFullPath(Path.GetDirectoryName(path));
                CheckFolderPath(map);
                File.Create(path).Dispose();
            }
        }
        /// <summary>
        /// 判断文件夹路径是否存在，不存在则创建文件夹
        /// </summary>
        /// <param name="path">文件夹全路径</param>
        public static void CheckFolderPath(string path)
        {
            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }
        }
        
        /// <summary>
        /// 上传文件自动加时间戳文件加，按时间戳生成文件名的文件保存，并返回保存后的相对路径
        /// </summary>
        /// <param name="file">上传的文件</param>
        /// <param name="FileUpladAudio">保存的相对路径</param>
        /// <param name="message">输出信息</param>
        /// <returns></returns>
        public static bool SaveAutoName(HttpPostedFileBase file, string FileUpladAudio, out string message)
        {
            bool result = false;
            var dt = DateTime.Now.ToString("yyyyMMdd");
            var uploadPath = System.Web.HttpContext.Current.Server.MapPath("~" + FileUpladAudio) + dt + "\\";
            if (file == null)
            {
                message = "NoFile";
                return result;
            }
            CheckFolderPath(uploadPath);
            string fileName = file.FileName;
            string ext = file.FileName.Substring(file.FileName.LastIndexOf('.'));
            fileName = DateTime.Now.Ticks + ext;
            file.SaveAs(uploadPath + fileName);
            string returnData = dt + "/" + fileName;
            result = true;
            message = FileUpladAudio + returnData;
            return result;
        }
        /// <summary>
        /// 生成缩略图jpg
        /// </summary>
        /// <param name="sourceFile">原始图片文件全路径</param>
        /// <param name="outputFile">输出文件全路径</param>
        /// <param name="quality">质量压缩比</param>
        /// <param name="multiple">收缩倍数(0为不收缩)</param>
        /// <param name="maxWidth">图片最大宽度(0为不限制)</param>
        /// <param name="maxHeight">图片最大高度(0为不限制)</param>
        /// <returns>成功返回true,失败则返回false</returns>
        public static bool GetThumImage(String sourceFile, String outputFile, long quality = 50, int multiple = 0, int maxWidth = 0, int maxHeight = 0)
        {
            try
            {
                long imageQuality = quality;
                using (Bitmap sourceImage = new Bitmap(sourceFile))
                {
                    ImageCodecInfo myImageCodecInfo = GetEncoderInfo("image/jpeg");
                    System.Drawing.Imaging.Encoder myEncoder = System.Drawing.Imaging.Encoder.Quality;
                    EncoderParameters myEncoderParameters = new EncoderParameters(1);
                    EncoderParameter myEncoderParameter = new EncoderParameter(myEncoder, imageQuality);
                    myEncoderParameters.Param[0] = myEncoderParameter;
                    float xWidth = sourceImage.Width;
                    float yWidth = sourceImage.Height;
                    float x = xWidth;
                    float y = yWidth;
                    if (multiple > 0)
                    {
                        x = xWidth / multiple;
                        y = yWidth / multiple;
                    }
                    if (maxWidth > 0 && x > maxWidth)
                    {
                        x = maxWidth;
                        y = yWidth / xWidth * maxWidth;
                    }
                    if (maxHeight > 0 && y > maxHeight)
                    {
                        x = xWidth / yWidth * maxHeight;
                        y = maxHeight;
                    }
                    using (Bitmap newImage = new Bitmap((int)(x), (int)(y)))
                    {
                        Graphics g = Graphics.FromImage(newImage);

                        g.DrawImage(sourceImage, 0, 0, x, y);
                        g.Dispose();
                        newImage.Save(outputFile, myImageCodecInfo, myEncoderParameters);
                    }
                    return true;
                }
            }
            catch
            {
                return false;
            }
        }
        /// <summary>
        /// 裁剪图片
        /// </summary>
        /// <param name="sourceFile">原始图片文件全路径</param>
        /// <param name="outputFile">输出文件全路径</param>
        /// <param name="x">裁剪起始点的x坐标(-1为横向居中截取)</param>
        /// <param name="y">裁剪起始点的y坐标(-1为纵向居中截取)</param>
        /// <param name="width">裁剪宽度</param>
        /// <param name="height">裁剪高度</param>
        /// <returns></returns>
        public static bool GetCutImage(String sourceFile, String outputFile, int x = 0, int y = 0, int width = 0, int height = 0)
        {
            try
            {
                using (Bitmap sourceImage = new Bitmap(sourceFile))
                {
                    #region 截取长度为0的方向不截取
                    if (width <= 0)
                    {
                        width = sourceImage.Width;
                    }
                    if (height <= 0)
                    {
                        height = sourceImage.Height;
                    }
                    #endregion
                    #region 居中处理
                    if (x == -1)
                    {
                        if (width < sourceImage.Width)
                        {
                            x = (sourceImage.Width - width) / 2;
                        }
                        else
                        {
                            x = 0;
                        }
                    }
                    if (y == -1)
                    {
                        if (height < sourceImage.Height)
                        {
                            y = (sourceImage.Height - height) / 2;
                        }
                        else
                        {
                            y = 0;
                        }
                    }
                    #endregion
                    #region 防止溢出
                    if (x >= sourceImage.Width)
                    {
                        x = sourceImage.Width - 1;
                    }
                    if (y >= sourceImage.Height)
                    {
                        y = sourceImage.Height - 1;
                    }
                    if (width + x > sourceImage.Width)
                    {
                        width = sourceImage.Width - x;
                    }
                    if (height + y > sourceImage.Height)
                    {
                        height = sourceImage.Height - y;
                    }
                    #endregion
                    Bitmap newImage = sourceImage.Clone(new Rectangle(x, y, width, height), sourceImage.PixelFormat);
                    newImage.Save(outputFile);
                    return true;
                }
            }
            catch
            {
                return false;
            }
        }
        /// <summary>
        /// 缩放并截取
        /// </summary>
        /// <param name="sourceFile">原始图片文件全路径</param>
        /// <param name="outputFile">输出文件全路径</param>
        /// <param name="width">要求宽度</param>
        /// <param name="height">要求高度</param>
        /// <returns></returns>
        public static bool GetCutThumImage(String sourceFile, String outputFile, int width = 0, int height = 0)
        {
            try
            {
                using (Bitmap sourceImage = new Bitmap(sourceFile))
                {
                    #region 尺寸都是0或者图片小则直接转存
                    if ((width == 0 && height == 0) || (sourceImage.Width <= width && sourceImage.Height <= height))
                    {
                        sourceImage.Save(outputFile);
                        return true;
                    }
                    #endregion
                    #region 只有一个尺寸、原图宽高比和要求宽高比一致的 只缩小不截取
                    if (width == 0 || height == 0 || sourceImage.Width * height == width * sourceImage.Height)
                    {
                        return GetThumImage(sourceFile, outputFile, 50, 0, width, height);
                    }
                    #endregion
                    #region 太宽按照高缩放，太高按照宽缩放
                    var thumPath = outputFile + ".thum." + System.IO.Path.GetExtension(outputFile);//缩放路径
                    var thum = false;//缩放结果
                    if (sourceImage.Width * height > width * sourceImage.Height)//太宽
                    {
                        thum = GetThumImage(sourceFile, thumPath, 50, 0, 0, height);
                    }
                    else if (sourceImage.Width * height < width * sourceImage.Height)//太高
                    {
                        thum = GetThumImage(sourceFile, thumPath, 50, 0, width, 0);
                    }
                    #endregion
                    #region 缩放后截取中间的部分
                    if (!thum)
                    {
                        return thum;
                    }
                    return GetCutImage(thumPath, outputFile, -1, -1, width, height);
                    #endregion
                }
            }
            catch
            {
                return false;
            }
        }

        /// <summary>  
        /// 获取图片编码信息  
        /// </summary>  
        private static ImageCodecInfo GetEncoderInfo(String mimeType)
        {
            int j;
            ImageCodecInfo[] encoders;
            encoders = ImageCodecInfo.GetImageEncoders();
            for (j = 0; j < encoders.Length; ++j)
            {
                if (encoders[j].MimeType == mimeType)
                    return encoders[j];
            }
            return null;
        }  
    }
}
